package com.lin.linchatgpt.config;

import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * Copyright(C),2022年-2022,霖霖
 *
 * @author 霖霖
 * @version 1.0
 * @date 2023/7/19 8:54
 * @Description 线程池配置
 */

@Configuration
@Slf4j
public class ThreadPoolConfig {

    @Value("${lin-thread-pool.core-pool-size}")
    private int corePoolSize;
    @Value("${lin-thread-pool.max-pool-size}")
    private int maxPoolSize;
    @Value("${lin-thread-pool.keep-alive-seconds}")
    private int keepAliveTime;
    @Value("${lin-thread-pool.queue-capacity}")
    private int queueCapacity;
    @Value("${lin-thread-pool.thread-name-prefix}")
    private String threadNamePrefix;
    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        return new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(queueCapacity),
                new MyThreadFactory(),
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }

    class MyThreadFactory implements ThreadFactory {
        @Override
        public Thread newThread(@NotNull Runnable r) {
            Thread thread = new Thread(r);
            thread.setName(threadNamePrefix);
            //异常自定义处理
            thread.setUncaughtExceptionHandler((exceptionThread, exception) -> log.error("线程:{}:::发生错误{}", exceptionThread.getName(), exception.getMessage()));
            return thread;
        }
    }
}
